import json
import os


def file_path(filename: str, curr: bool = False):
    if curr:
        if filename.startswith("/") or filename.startswith("\\"):
            return os.getcwd() + filename
        else:
            return os.getcwd() + "/" + filename
    else:
        return filename


def open_file(filename: str, mode: str = "r", encoding: str = "utf-8", curr: bool = False):
    return open(file_path(filename, curr), mode=mode, encoding=encoding)


def read_file(filename: str, mode: str = "r", encoding: str = "utf-8", curr: bool = False):
    file = None
    try:
        file = open_file(filename, mode=mode, encoding=encoding, curr=curr)
        return file.read()
    finally:
        if file is not None:
            file.close()


def read_file_str(filename: str, mode: str = "r", encoding: str = "utf-8", curr: bool = False):
    return str(read_file(filename, mode=mode, encoding=encoding, curr=curr))


def read_file_json(filename: str, mode: str = "r", encoding: str = "utf-8", curr: bool = False):
    return json.loads(read_file(filename, mode=mode, encoding=encoding, curr=curr))


def write_str(filename: str, mode: str = "w", encoding: str = "utf-8", curr: bool = False, data=None):
    if data is not None:
        file = None
        try:
            file = open(file_path(filename, curr), mode=mode, encoding=encoding)
            file.write(data)
        finally:
            if file is not None:
                file.close()
    else:
        return None


def write_bytes(filename: str, mode: str = "wb", curr: bool = False, data=None):
    if data is not None:
        file = None
        try:
            file = open(file_path(filename, curr), mode=mode)
            file.write(data)
        finally:
            if file is not None:
                file.close()
    else:
        return None
